<?php
namespace sms\alisms;
use org\Http;

class alisms
{

    const API_URL='https://dysmsapi.aliyuncs.com';
    protected $config;


    public function __construct($config)
    {
        $this->config=$config;
    }

    private  function jiexiConf($templateCodeConf){

        $tplList = explode("\n", $templateCodeConf);
        $tplArr = [];
        foreach ($tplList as $v) {
            $_arr = explode("、", $v);
            $tplArr[$_arr[0]] =[
                'template_code'=>$_arr[1],
                'replace_variate'=>$_arr[2]
            ];
        }

        return $tplArr;
    }

    public function send($toObject,$content,$code,$tplId)
    {
        $arr=$this->jiexiConf($this->config['template_code']);
        if(!isset($arr[$tplId])){
            dd('系统中的阿里云配置->模版CODE 错误');
        }
        $conf=$arr[$tplId];
        // 必填: 短信接收号码
        $params["PhoneNumbers"] = $toObject;
        // 必填: 短信签名
        $params["SignName"] = $this->config['signature'];

        $params["TemplateCode"] = $conf['template_code'];

        $params["TemplateParam"] = json_encode([$conf['replace_variate']=>$code], JSON_UNESCAPED_UNICODE);

        $helper = new SignHelper;
        // 此处可能会抛出异常，注意catch
        $signStr = $helper->getSignUrl($this->config['access_key_id'], $this->config['access_key_secret']
            , array_merge($params, [
                "RegionId" => "cn-hangzhou",
                "Action" => "SendSms",
                "Version" => "2017-05-25",
            ])
        );
        $result = Http::get(self::API_URL.$signStr);
        $data=json_decode($result,true);
        if ($data['Code']=="OK") {
            return array('code' => 1, 'msg' => '发送成功');
        } else {
            return array('code' => 0, 'msg' => $data['Message'].'，请联系站长');
        }
    }

}